package net.lzy.pub;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Recv3 {
    private final static String EXCHANGE_NAME = "exchange_fanout";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("114.132.74.230");
        factory.setUsername("admin");
        factory.setPassword("pddlzy123.");
        factory.setVirtualHost("/dev");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //绑定交换机，设置fanout类型
        channel.exchangeDeclare(EXCHANGE_NAME,BuiltinExchangeType.FANOUT);
        //获取队列名称-使用默认队列
        String queue = channel.queueDeclare().getQueue();
        //队列绑定交换机
        channel.queueBind(queue,EXCHANGE_NAME,"");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);

                System.out.println(new String(body, StandardCharsets.UTF_8));
                //⼿⼯确认消息消费，不是多条确认
                channel.basicAck(envelope.getDeliveryTag(), false);
            }

        };
        //关闭自动确认
        channel.basicConsume(queue,false,consumer);

    }
}
